package asteroids.statement;

import asteroids.FlyingObject;
import asteroids.model.programs.*;
import asteroids.statement.Statement.StatementType;
import asteroids.Ship;
import asteroids.expression.*;

public class WhileStatement extends Statement {

	private Statement statement;
	private Expression exp;

	public WhileStatement(Expression e, Statement s) {
		if (!(e instanceof Expression))
			e = new asteroids.expression.BooleanLiteral(false);
		this.exp = e;
		if (s != null)
			this.statement = s;
		else
			this.statement = new SkipStatement();
	}

	@Override
	public void execute(Program program) {
		int i = 0;
		while (!this.finished && i < 10) {
		if (this.exp instanceof BooleanExpression) {
			if (((BooleanExpression) this.exp).getValue(program)) {
				if (this.statement.isFinished()) {
					statement.loop();
				}
				this.statement.execute(program);
				if ((statement.getType() == StatementType.ACTION)
						|| (statement.getBreaker())) {
					this.setBreaker(true);
					statement.setBreaker(false);
					break;
				}
			} else {
				this.finished = true;
			}

		} else if (this.exp instanceof Variable
				&& ((Variable) this.exp).getRef(program) instanceof BooleanExpression) {
			if (((Boolean) ((Variable) this.exp).getValue(program))) {
				if (this.statement.isFinished()) {
					statement.loop();
				}
				this.statement.execute(program);
				if ((statement.getType() == StatementType.ACTION)
						|| (statement.getBreaker())) {
					this.setBreaker(true);
					statement.setBreaker(false);
					break;
				}
			} else {
				this.finished = true;
			}
		} else {
			finished = true;
		}
		i++;}

	}

	@Override
	public int getSize() {
		return statement.getSize();
	}
}
